from datetime import datetime

from influxdb import InfluxDBClient
from sqlalchemy import create_engine, text

engine = create_engine(
    'mysql+pymysql://isyscore:Isysc0re@172.16.200.218:23306/bap_data_warehouse?charset=utf8&connect_timeout=5')
client = InfluxDBClient('172.16.200.218', 28086, database='isc_dmc')
now = datetime.now()


def minute(t):
    if 0 <= t.minute < 15:
        return 0
    elif 15 <= t.minute < 30:
        return 15
    elif 30 <= t.minute < 45:
        return 30
    elif 45 <= t.minute < 60:
        return 45

start = datetime(now.year, now.month, now.day)
current = datetime(now.year, now.month, now.day, now.hour, minute(now))
total_consume = 0
try:
    device_lst = ['BPD-DB-22', 'BPD-DB-19', 'BPD-DB-18', 'BPD-DB-17', 'BPD-DB-16', 'BPD-DB-8', 'BPD-DB-7', 'BPD-DB-4']
    for i in device_lst:
        start_sql = "select value from device_attr_double where devId='{}' and identifier = 'EPI' and time >= {} order by time asc limit 1".format(
            i, int(start.timestamp() * 1000000000))
        end_sql = "select value from device_attr_double where devId='{}' and identifier = 'EPI' and time >= {} order by time desc limit 1".format(
            i, int(start.timestamp() * 1000000000))
        zero_lst = [float(p['value']) for p in client.query(start_sql).get_points()]
        curr_lst = [float(p['value']) for p in client.query(end_sql).get_points()]
        if len(zero_lst) > 0 and len(curr_lst) > 0:
            accum = curr_lst[0] - zero_lst[0]
        else:
            accum = 0
        total_consume += accum

    engine.execute('''
        create table if not exists ST_ELEC_CONSUME
        (
        create_time datetime primary key not null,
        total_consume double null
        )
        ''')
    v = {'create_time': current, 'total_consume': round(total_consume, 2)}
    table_name = "ST_ELEC_CONSUME"
    ks = ','.join(['`{}`'.format(k) for k in v.keys()])
    vs = ','.join([':{}'.format(v) for v in v.keys()])
    stmt = text("""replace into {} ({}) values ({})""".format(table_name, ks, vs))
    # engine.execute(stmt, v)
except Exception as e:
    raise e
finally:
    client.close()